package com.atguigu.teach.mytask;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ShareResource{
    int flag=1;//默认约定：1 ：A 2 ：B 3 ：C。。。。。
    Lock lock= new ReentrantLock();
    Condition condition1=lock.newCondition();
    Condition condition2=lock.newCondition();
    Condition condition3=lock.newCondition();
    public  void print5(){

        lock.lock();
        try{
            //1判断
            while(flag!=1){
                condition1.await();
            }
            //2干活
            for (int i = 1; i <=5 ; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+":"+i);
            }
            flag=2;
            condition2.signal();
            //3通知
            //4注意下半场各部分


        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }

    public  void print10(){

        lock.lock();
        try{
            //1判断
            while(flag!=2){
                condition2.await();
            }
            //2干活
            for (int i = 1; i <=10 ; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+":"+i);
            }
            flag=3;
            condition3.signal();
            //3通知
            //4注意下半场各部分


        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }

    public  void print15(){

        lock.lock();
        try{
            //1判断
            while(flag!=3){
                condition3.await();
            }
            //2干活
            for (int i = 1; i <=15 ; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+":"+i);
            }
            flag=1;
            condition1.signal();
            //3通知
            //4注意下半场各部分


        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }

}
public class MyThreadOrderAccess {

    /**
     * @name:
     * @params:
     * @description:多线程调用  A B C
     * 三个线程启动，要求如下
     * AA 打印5次 BB打印10次 CC打印15次
     * 来10轮
     * @return:
     * @exception/throws:
     * @author: zxb
     * @date:   2021/10/22
     */
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                shareResource.print5();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                shareResource.print10();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                shareResource.print15();
            }
        },"C").start();
    }
}
